<template>
  <a-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="mainId">
      <a-button @click="handleAdd" type="primary" icon="plus" v-show="!isChecked">新增</a-button>
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('调拨单明细')">导出</a-button>-->
      <!--      <a-upload-->
      <!--        name="file"-->
      <!--        :showUploadList="false"-->
      <!--        :multiple="false"-->
      <!--        :headers="tokenHeader"-->
      <!--        :action="importExcelUrl"-->
      <!--        @change="handleImportExcel">-->
      <!--          <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <a-dropdown v-if="selectedRowKeys.length > 0 && !isChecked">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="materialCode" slot-scope="text, record">
          <div>
            <a-select
              :dropdownMatchSelectWidth="false"
              :showSearch="true"
              style="width: 100px"
              :value="selectValue"
              :maxTagCount="10"
              @search="searchMaterial"
              @blur="clearMaterialData"
              @select="changeRecord($event, record)"
              @popupScroll="popupScroll"
              :filter-option="false"
              v-if="record.selectable"
            >
              <a-select-option v-for="(item, index) in materialData" :key="index">
                <span v-for="(i, index) in materialField" :key="index">
                  {{ item[i] }}
                  <a-divider type="vertical" style="background-color: #0c8fcf"></a-divider>
                </span>
              </a-select-option>
            </a-select>
            <template v-else slot-scope="text, record">
              {{ record.materialCode }}
            </template>
          </div>
        </template>
        <template slot="number" slot-scope="text, record">
          <a-input-number v-model:value="record.number" v-if="record.selectable"></a-input-number>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="inputWarehouse" slot-scope="text, record">
          <j-dict-select-tag
            v-model:value="record.inputWarehouse"
            v-if="record.selectable"
            dict-code="hf_warehouse,warehouse_name,id"
            @change="changInputWarehouse($event, record)"
            style="width: 100%;"
          ></j-dict-select-tag>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="outputWarehouse" slot-scope="text, record">
          <j-dict-select-tag
            v-model:value="record.outputWarehouse"
            v-if="record.selectable"
            dict-code="hf_warehouse,warehouse_name,id"
            @change="changOutputWarehouse($event, record)"
            style="width: 100%;"
          ></j-dict-select-tag>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <div class="editable-row-operations" v-show="record.status !== 1">
            <span v-if="record.editable">
              <a @click="() => save(record)">保存</a>
              <a-divider type="vertical" style="background-color: grey"></a-divider>
              <a @click="() => cancel(record)">取消</a>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="edit(record)" v-show="!isChecked">编辑</a>
              <a-divider type="vertical" style="background-color: grey" v-show="!isChecked"></a-divider>
              <a :disabled="editingKey !== ''" @click="handleDelete(record.id)" v-show="!isChecked">删除</a>
            </span>
          </div>
        </template>
      </a-table>
    </div>

    <hfAllocateDetail-modal ref="modalForm" @ok="modalFormOk" :mainId="mainId"></hfAllocateDetail-modal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HfAllocateDetailModal from './modules/HfAllocateDetailModal'
import { HfIODetailMixin } from '@/mixins/HfIODetailMixin'
import { postAction, putAction } from '@api/manage'
import { ajaxGetDictItems } from '@api/api'

export default {
  name: 'HfAllocateDetailList',
  mixins: [JeecgListMixin, HfIODetailMixin],
  components: { HfAllocateDetailModal },
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    }
  },
  sourceSerial: {
    type: String,
    default: '',
    required: false
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['sourceId'] = val
          this.loadData(1)
        }
      }
    }
  },
  data() {
    return {
      description: '调拨单管理页面',
      disableMixinCreated: true,
      isChecked: false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '调出仓库',
          align: 'center',
          dataIndex: 'outputWarehouse_dictText',
          scopedSlots: { customRender: 'outputWarehouse' }
        },
        {
          title: '调入仓库',
          align: 'center',
          dataIndex: 'inputWarehouse_dictText',
          scopedSlots: { customRender: 'inputWarehouse' }
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/warehouse/hfAllocate/listHfAllocateDetailByMainId',
        delete: '/warehouse/hfAllocate/deleteHfAllocateDetail',
        deleteBatch: '/warehouse/hfAllocate/deleteBatchHfAllocateDetail',
        exportXlsUrl: '/warehouse/hfAllocate/exportHfAllocateDetail',
        importUrl: '/warehouse/hfAllocate/importHfAllocateDetail',
        add: '/warehouse/hfAllocate/addHfAllocateDetail',
        edit: '/warehouse/hfAllocate/editHfAllocateDetail'
      },
      dictOptions: {}
    }
  },
  created() {},
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importUrl}/${this.mainId}`
    }
  },
  methods: {
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    save(record) {
      if (record.number === null || record.number === undefined) {
        this.$message.error('请输入数量')
        return
      }
      let param = Object.assign({}, record)
      param['sourceId'] = this.mainId
      param['sourceSerial'] = this.sourceSerial
      this.loading = false
      if (param.add) {
        postAction(this.url.add, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      } else {
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      }
    },
    changeRecord(index, record) {
      //获取物料信息
      const newData = [...this.dataSource]
      //找到选中行的数据
      const target = this.materialData[index]
      //找到当前行的数据
      const current = newData.find((item, index) => {
        return record.id === item.id
      })
      Object.keys(target).forEach(key => {
        if (target[key] === null) {
          target[key] = ''
        }
      })
      //设置数据
      current.materialId = target.id
      current.materialCode = target.materialCode
      current.materialName = target.materialName
      current.sap = target.sap
      current.unit_dictText = target.unit_dictText
      current.unit = target.unit
      current.materialType_dictText = target.materialType_dictText
      current.materialType = target.materialType
      current.inputWarehouse = target.warehouse
      current.inputWarehouse_dictText = target.warehouse_dictText
      current.perNumber = target.perNumber
      this.selectValue = target.materialCode
      this.editingKey = ''
      this.dataSource = newData
      // this.materialData = this.materialData
    },
    changInputWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.inputWarehouse_dictText = dictOptions.find(item => item.value === record.inputWarehouse).text
          target.inputWarehouse = warehouse
          this.dataSource = newData
        }
      })
    },
    changOutputWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.outputWarehouse_dictText = dictOptions.find(item => item.value === record.outputWarehouse).text
          target.outputWarehouse = warehouse
          this.dataSource = newData
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
